package xdu.lz.stage2_design_pattern.chapter14_countDown_pattern;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.stream.IntStream;

public class JDKCountDown {

    private static final Random random = new Random(System.currentTimeMillis());

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(5);
        //第一阶段
        System.out.println("第一阶段：多线程处理任务");
        IntStream.rangeClosed(1,5).forEach(
                i-> new Thread(()->{
                    System.out.println(Thread.currentThread().getName()+" is working.");
                    latch.countDown();
                    try {
                        Thread.sleep(random.nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                },""+i).start());
        //让所有的线程都wait住。最后一个countDown时候，统一让所有线程都执行
        latch.await();
        //第二阶段
        System.out.println("准备第二阶段：");
        System.out.println("FINISH");
    }
}
